import React from 'react';
import { Modal, Button, Tree } from 'antd';

const TreeNode = Tree.TreeNode;

class Components extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKeys: [],
      allSelectedKeys: [], //包含了半选父节点的
    };
  }

  onOk = () => {
    const { allSelectedKeys } = this.state;
    this.props.submit(allSelectedKeys);
  };

  onCheck = (checkedKeys, info) => {
    this.setState({
      selectedKeys: checkedKeys,
      allSelectedKeys: [...checkedKeys, ...info.halfCheckedKeys],
    });
  };

  componentWillReceiveProps(nextProps) {
    let arr = [];
    const check = (treeData, checkedKeys) => {
      treeData.map(i=>{
        if(i.children) {
          return check(i.children,checkedKeys)
        }else {
          for(let j of checkedKeys) {
            if(j === i.key) {
              arr.push(j)
            }
          }
        }
      })

    };
    if (nextProps.selectedArr !== this.state.selectedKeys) {
      check(nextProps.treeData, nextProps.selectedKeys);
      this.setState({
        selectedKeys: arr,
      });
    }
  }

  /**
   * 设置子节点
   */
  renderTreeNodes = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });
  };

  render() {
    const { visible, treeData, toggleVisible } = this.props;
    const { selectedKeys } = this.state;

    return (
      <Modal
        okText="保存"
        cancelText="取消"
        title="角色绑定"
        bodyStyle={{ height: '400px', overflowY: 'scroll' }}
        visible={visible}
        onCancel={toggleVisible}
        onOk={this.onOk}
      >
        <Tree
          checkable
          onExpand={this.onExpand}
          style={{ display: 'inline' }}
          checkedKeys={selectedKeys}
          onCheck={this.onCheck}
        >
          {this.renderTreeNodes(treeData)}
        </Tree>
      </Modal>
    );
  }
}

export default Components;
